/**
 * @constructor 请求二次封装
 * @param { string } title - 基于 axios 二次封装请求
 * @param { string } author - Sky_sjr
 * */

import axios from 'axios'
import common from './common';
import define from './define'

import { Notify } from 'vant';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: define.TIMEOUT
})

service.interceptors.request.use(config => {
  if (common.getStorage('token')) {
    config.headers.token = common.getStorage('token') || ''
  }
  return config
})

service.interceptors.response.use(
  res => {
    if (res.status >= 200 && res.status < 300) {
      return res.data
    }
    const e = new Error('API 接口异常！')
    e.response = res
    return Promise.reject(e)
  },
  error => {
    try {
      const { msg } = error.response.data
      msg && Notify({ type: 'danger', message: msg })
    } catch {
      const { message } = error.response.data
      // 危险通知
      message && Notify({ type: 'danger', message });
    }
    return Promise.reject(error);
  }
)

export default service